/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package general;

/**
 *
 * @author foliveira
 */
public class UDPTestConnection {

  private UDPConnection connection;
  private String host;
  private int port;
  private UDPMessage message;
  private RequestBuilder request;
  private String echo;
  /*
   * 
   * @aut
   */

  public UDPTestConnection(String host) {

    String[] parts;

    echo = String.format("%s:%s:%s:%s:%s:%s", 0, Commands.ECHO, 0, 0, 0, 0);

    try {
      parts = breakParts(host);
      setHost(parts[0]);
      setPort(Integer.parseInt(parts[1]));

    } catch (Exception e) {
      e.printStackTrace();
    }

    connection = new UDPConnection();
    setRequest();
    
  }

  // cria arequisição
  private void setRequest() {
    this.request = new RequestBuilder(echo);
  }

  // testa conexao com um ente de rede
  public boolean connected() {
    boolean successfull = false;


    try {

      connection.setTimeOut(50000);
      message = new UDPMessage(connection);
      message.to(this.getHost(), this.getPort());
      message.send(request.getRequest().toString());

      message.receive(); 
      connection.close(); 
      successfull = true;

    } catch (Exception e) {
      e.printStackTrace();
    }

    return successfull;
  }

  public String getHost() {
    return host;
  }

  private void setHost(String host) {
    this.host = host;
  }

  public int getPort() {
    return port;
  }

  private void setPort(int port) {
    this.port = port;
  }

 
  private String[] breakParts(String host) {
    String[] parts = null;

    try {

      parts = host.split(":");

    } catch (Exception e) {
      e.printStackTrace();
    }
    return parts;
  }
}
